<?php

namespace common\core\server;

use yii\base\Model;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class CacheActiveRecord extends Model
{

    protected $cacheKey;
    protected $cache;

    public function init()
    {
        parent::init();

        if ($this->cacheKey === null) {
            $this->cacheKey = get_called_class();
        }

        if ($this->cache === null) {
            $this->cache = \Yii::$app->commonCache;
        }

        $params = $this->cache->get($this->cacheKey);
        if (!empty($params)) {
            $data = Json::decode($params);
            $this->setAttributes($data);
        }
    }

    /**
     * 获得有效参数
     *
     * @param array $params
     *
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function filterParams(array $params)
    {
        return ArrayHelper::getValue($params, $this->formName(), $params);
    }

    /**
     * 添加 / 更新
     *
     * @param array  $params
     * @param string $isDeleteName
     * @param bool   $isSave
     *
     * @return object
     * @throws \yii\base\InvalidConfigException
     */
    public function updateByParams(array $params, $isSave = true, $isDeleteName = 'is_delete')
    {
        $data = $this->filterParams($params);
        $this->setAttributes($data);
        $this->cache->set($this->cacheKey, Json::encode($data));
        return $this;
    }

    /**
     * 通过id删除数据
     *
     * @param int    $id
     * @param string $isDeleteName
     *
     * @return
     */
    public function deleteById($id, $isDeleteName = 'is_delete')
    {
        return $this->cache->delete($this->cacheKey);
    }

}